﻿using Application.Commons.Data;
using AutoMapper;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace NM.Module.Cust.API.Commands.ChangePassword;

#nullable disable

/// <summary>
/// 修改密码
/// </summary>
public class ChangePasswordCommand : IRequest<Result<long>>
{
    /// <summary>
    /// 用户主键
    /// </summary>
    [Required(ErrorMessage = "用户主键必传")]
    public long CustomerId { get; set; }

    /// <summary>
    /// 老密码
    /// </summary>
    [Required(ErrorMessage = "老密码必填")]
    public string OldPassword { get; set; }

    /// <summary>
    /// 新密码
    /// </summary>
    [Required(ErrorMessage = "新密码必填")]
    public string NewPassword { get; set; }

    /// <summary>
    /// 确认新密码
    /// </summary>
    [Compare(nameof(NewPassword), ErrorMessage = "确认新密码不正确")]
    public string ConfirmNewPassword { get; set; }
}

public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, Result<long>>
{
    private readonly ApplicationDbContext _context;

    public ChangePasswordCommandHandler(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Result<long>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
    {
        var item = await _context.Customers.SingleOrDefaultAsync(x => x.Id == request.CustomerId, cancellationToken);
        ExceptionHelper.ThrowIfNull(item, "用户不存在");
        ExceptionHelper.ThrowIfFalse(item.VerifyPassword(request.OldPassword), "老密码错误");

        item.HashPassword(request.NewPassword);
        _context.Update(item);
        await _context.SaveChangesAsync(cancellationToken);

        return await Result<long>.SucceedAsync(item.Id);
    }
}